import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import copy from "rollup-plugin-copy"; // 引入 rollup-plugin-copy
import path from "node:path";
export default defineConfig({
  root: "src/",
  plugins: [
    vue(),
    copy({
      targets: [
        { src: "manifest.json", dest: "dist" }, // 复制 manifest.json 到 dist 目录
        { src: "src/assets/*", dest: "dist/assets" }, // 复制 src/icons/** 到 dist/icons 目录
      ],
    }),
  ],
  resolve: {
    alias: {
      "@": path.resolve(process.cwd(), "src"),
    },
  },
  build: {
    outDir: path.resolve(process.cwd(), "dist"),
    assetsDir: "./src/assets",
    rollupOptions: {
      input: {
        newTab: path.resolve(process.cwd(), "src/NewTab/index.html"),
        popup: path.resolve(process.cwd(), "src/Popup/index.html"),
        background: path.resolve(
          process.cwd(),
          "src/Background/service-worker.ts"
        ),
      },
      output: {
        assetFileNames({ originalFileName }) {
          const chunks = originalFileName?.split("/");
          if (originalFileName && chunks && chunks.length >= 3) {
            return `${chunks[0]}/${chunks[1]}/[name].[ext]`;
          }
          return "assets/[name].[ext]";
        },
        chunkFileNames: "js/[name].js", // 代码分割中产生的 chunk
        entryFileNames: (chunkInfo) => {
          // 入口文件
          const baseName = path.basename(
            chunkInfo.facadeModuleId!,
            path.extname(chunkInfo.facadeModuleId!)
          );
          const saveArr = ["content", "service-worker"];
          return `[name]/${
            saveArr.includes(baseName) ? baseName : chunkInfo.name
          }.js`;
        },
        name: "[name].js",
      },
    },
  },
});
